from django.test import TestCase
from django.utils import timezone
from api.models import User, Role, RelationUserRole


def create_user(username, password):
    user = User.objects.create(
        username=username,
        password=password,
        phone="",
        email="",
        department="系统管理",
        description="",
        create_time=timezone.now(),
        last_edit_time=timezone.now(),
    )


def create_role(level, code):
    Role.objects.create(
        level=level,
        name="test",
        code=code,
        description="管理员",
        create_time=timezone.now(),
        last_edit_time=timezone.now(),
        fault_injection=True,
        data_monitor=True,
        detection=True,
        diagnosis=True,
        manage=True,
        RecordShow=True,
    )


def get_token(client, username, password):
    response = client.post(
        "/login", {"username": username, "password": password}, "application/json"
    )
    return response.json()["data"]["token"]


class TestAccount(TestCase):
    def __init__(self, methodName: str = "runTest") -> None:
        super().__init__(methodName)

    def test_login(self):
        create_user("aiops@admin", "nkcs@aiops")
        test_cases = [
            {
                "username": "aiops@admin",
                "password": "123456",
            },  # password ==
            {
                "username": "aiops@admin",
                "password": "nkcs@aiops",
            },  # password !=
        ]
        response = self.client.post("/login", test_cases[0], "application/json")
        self.assertEqual(response.status_code, 400)
        response = self.client.post("/login", test_cases[1], "application/json")
        self.assertEqual(response.status_code, 200)

    def test_info(self):
        create_user("aiops@admin", "nkcs@aiops")
        token = get_token(self.client, "aiops@admin", "nkcs@aiops")
        # role_id = []
        response = self.client.get("/info", HTTP_AUTHORIZATION=f"token {token}")
        self.assertEqual(0, len(response.json()["data"]["ownRoles"]))
        # role_id = [...]
        create_role(1, "admin")
        RelationUserRole.objects.create(user_id=1, role_id=1)
        create_role(2, "user")
        RelationUserRole.objects.create(user_id=1, role_id=2)
        response = self.client.get("/info", HTTP_AUTHORIZATION=f"token {token}")
        self.assertEqual(2, len(response.json()["data"]["ownRoles"]))

    def test_logout(self):
        r""" """
        response = self.client.post("/logout")
        self.assertEqual(response.status_code, 200)
